package jsonx

import (
	"fmt"
	"time"
)

type Time time.Time

func (m Time) Len() int {
	return 37
}

func (m Time) MarshalJsonx(buf []byte) (int, error) {
	v := time.Time(m)
	if v.IsZero() {
		return 0, nil
	}
	var i int
	var tb [35]byte
	i += copy(buf[i:], `"`)
	i += copy(buf[i:], v.AppendFormat(tb[:0], time.RFC3339Nano))
	i += copy(buf[i:], `"`)
	return i, nil
}

func (m Time) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf(`"%s"`, time.Time(m).Format(time.RFC3339Nano))), nil
}

func (m *Time) UnmarshalJSON(data []byte) error {
	t, err := time.Parse(`"`+time.RFC3339+`"`, string(data))
	if err != nil {
		return err
	}
	*m = Time(t)
	return nil
}

func (m Time) Format(layout string) string {
	return time.Time(m).Format(layout)
}

func (m Time) Sub(t1 Time) time.Duration {
	return time.Time(m).Sub(time.Time(t1))
}
